package com.liuboya.config.db;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 描述：
 *
 * @author yeyuan
 * @date 2021/08/17 17:48
 **/
@Configuration
@EnableConfigurationProperties
@MapperScan(basePackages = "com.liuboya.dao.weibo.*.mapper", sqlSessionTemplateRef = "weiboSqlSessionTemplate")
public class WeiBoDataSource {

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Bean(name = "weiboData")
    public DataSource sentinelData() {
        HikariDataSource druidDataSource = (HikariDataSource) DataSourceBuilder.create()
                .driverClassName(driverClassName)
                .url(url)
                .username(username)
                .password(password).build();
        druidDataSource.setMaximumPoolSize(30);
        return druidDataSource;
    }

    @Bean(name = "weiboSqlSessionFactory")
    public SqlSessionFactory sentinelSqlSessionFactory(@Qualifier("weiboData") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:sqlmap/weibo/*/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "weiboTransactionManager")
    public DataSourceTransactionManager sentinelTransactionManager(@Qualifier("weiboData") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "weiboSqlSessionTemplate")
    public SqlSessionTemplate sentinelSqlSessionTemplate(@Qualifier("weiboSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}